<?php

define("MATERIAL_TYPE_ARTICLE", 1);

class bpTag {
    function isExistTag($sTag) {
        $query = "SELECT id FROM tags WHERE name='$sTag'";
        $result = mysql_query($query);
        if (mysql_num_rows($result)) {
            return mysql_result($return, 0, "id");
        } else {
            return false;
        }
    }
    
    function addTag($sTag, $bNeedExist = true) {
        if ($bNeedExist) {
            if ($iTagId = bpTag::isExistTag($sTag)) {
                return $iTagId;
            }
        }
        $query = "INSERT INTO tags(name) VALUES('".mysql_real_escape_string($sTag)."')";
        mysql_query($query);
        return mysql_insert_id();
    }
    
    function addTagsToMaterial($aTags, $cMaterialType) {
        if (!empty($aTags) && is_string($aTags)) {
            $aTags = array($aTags);
        } elseif (!is_array($aTags)) {
            return false;
        }
        foreach ($aTags as $sTag) {
            bpTag::addTag($sTag, true);
        }
        
        return true;
    }
    
    function getTagsMaterial($iMaterialId, $cMaterialType) {
        $query = "SELECT id, name FROM tags_material INNER JOIN tags ON id=tag_id WHERE material_id='".(int)$iMaterialId."' AND material_type='".(int)$cMaterialType."' ";
        $result = mysql_query($query);
        $output = array();
        while ($row = mysql_fetch_assoc($result)) {
            $row["name"] = htmlspecialchars($row["name"]);
            $output[] = $row;
        }
        
        return $output;
    }
}
?>